package com.imooc.infra.repository;

import com.imooc.business.domain.Metadata;
import com.imooc.infra.mapping.MetadataMapping;
import com.imooc.infra.repository.entity.TDataCenterMetadata;
import com.imooc.infra.repository.service.ITDataCenterMetadataService;
import lombok.Setter;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author Tim
 * @Description:
 * @Version 1.0
 */
@Repository
public class MetaDataRepository {

    @Setter(onMethod_ = @Autowired)
    private ITDataCenterMetadataService metadataService;
    @Setter(onMethod_ = @Autowired)
    private MetadataMapping metadataMapping;

    public List<Metadata> listByRuleId(Long ruleId) {
        List<TDataCenterMetadata> metadatas = metadataService.listByRuleId(ruleId);
        return metadatas.stream().map(metadataMapping::toVo).collect(Collectors.toList());
    }

    public List<Metadata> saveMetadata(Long ruleId, List<Metadata> metadataList) {
        List<TDataCenterMetadata> entityList = metadataList.stream().map(metadataMapping::toEntity).
                peek(meta -> {
                    meta.setRuleId(ruleId);
                }).collect(Collectors.toList());
        boolean saveBatch = metadataService.saveBatch(entityList);
        if (saveBatch) {
            return entityList.stream().map(metadataMapping::toVo).collect(Collectors.toList());
        }
        return Lists.newArrayList();
    }
}
